import {ElMessageBox,ElMessage} from "element-plus"
import router from "../router/index"
import { getToken , delToken} from './store';
import Axios from "axios"
export const serviceUrl = process.env.VUE_APP_SERVICE_URL
//export const serviceUrl = 'http://192.168.0.100:3000'
const axios = Axios.create({
    baseURL:serviceUrl+"/api"
})
const whiteUrlSuffixArr = ['login','captcha']
axios.interceptors.request.use((config)=>{
    const whiteUrl = whiteUrlSuffixArr.find((item)=>config.url?.endsWith(item))
    if(!whiteUrl){
        config.headers.token = getToken()
    }
    return config
})
axios.interceptors.response.use(async (response)=>{
    if(response.status == 200){
        if(response.data.code == 400){
            ElMessage.error(response.data.message)
            return Promise.reject()
        }
        return response.data
    }
},async (err)=>{
    const {response} = err
    console.log(response)
    switch (response.status) {
        case 401:
            try {
                await ElMessageBox.confirm("登录信息已过期是否重新登录?", "提示", {
                    type: "warning",
                    cancelButtonText: '取消',
                    confirmButtonText: '确定'
                })
                delToken()
                location.reload()
            } catch (error) {
                console.log(error)
            }
            break;
        case 400:
            ElMessage.error(response.data.message);
            break
        case 500:
            ElMessage.error("服务器异常请联系管理员")
            break
        default :
            ElMessage.error(err.message)
    }
    return Promise.reject()
})
// eslint-disable-next-line
export function buildQueryString(data?: {[key: string]: any}): string{
    if(!data){
        return  ""
    }
    const queryStringArr: string[] = []
    for (const [key,value] of Object.entries(data)) {
        if(!value && value !== 0){
          continue
        }
        if (value instanceof Array){
            value.forEach(v=>{
                queryStringArr.push(`${key}=${typeof v ==='string'?v.trim() :v }`)
            })
            if (value.length ===1){
                queryStringArr.push(`${key}=`)
            }
        }else {
            queryStringArr.push(`${key}=${typeof value === 'string'?value.trim():value}`)
        }
    }
    let queryString = queryStringArr.join("&")
    if (queryString){
        queryString = "?"+queryString
    }
    return queryString
}
export interface Page<T>{
    currentPage: number;
    pageSize: number;
    total: number;
    totalPage: number;
    list: T[];
}
export default axios
